<?php

/**
 * smarty wrapper for codeigniter
 * Class CI_Smarty
 *
 * @author sunnyw
 */
ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR .
    FCPATH . 'vendor/smarty/smarty/libs');

require 'TplEngineInterface.php';
require 'Smarty.class.php';

class CI_Smarty extends Smarty implements TplEngineInterface
{
    const SMARTY_CONF_FILE='smarty';    //config/smarty.php

    protected $template_dir;
    protected $compile_dir;
    protected $config_dir;
    protected $cache_dir;

    private $_ci;

    function __construct()
    {
        parent::__construct();

        $this->_ci= &get_instance();
        $this->_ci->config->load(self::SMARTY_CONF_FILE);

        require_once 'Autoloader.php';
        Smarty_Autoloader::registerBC();
        log_message('debug', 'smarty autoloader loaded');

        $this->template_dir=$this->_ci->config->item('smarty_template_dir');
        $this->compile_dir=$this->_ci->config->item('smarty_compile_dir');
        $this->config_dir=$this->_ci->config->item('smarty_config_dir');
        $this->cache_dir=$this->_ci->config->item('smarty_cache_dir');

        $this->setTemplateDir($this->template_dir);
        $this->setCompileDir($this->compile_dir);
        $this->setConfigDir($this->config_dir);
        $this->setCacheDir($this->cache_dir);

//		$this->debugging = true;
//		$this->assign('APPPATH', APPPATH);
//		$this->assign('BASEPATH', BASEPATH);
		log_message('debug', "Smarty Class Initialized");

//		$this->tpl->left_delimiter = '<!--{';
//		$this->tpl->right_delimiter = '}-->';
        //禁止编译检查，优化项
//		$this->tpl->setCaching(Smarty::CACHING_LIFETIME_CURRENT);
//		$this->tpl->setCompileCheck(false);

//		$this->tpl->clearAllCache();

    }

    //渲染模版
    function render($template, $data = array(), $return = false)
    {
        foreach($data as $key => $val) {
            $this->assign($key, $val);
        }

        if($return == false) {
            $CI =& get_instance();
            if(method_exists($CI->output, 'set_output')) {
                $CI->output->set_output($this->fetch($template));
            }
            else {
                $CI->output->final_output = $this->fetch($template);
            }

        }
        else {
            return $this->fetch($template);
        }
    }

}